package com.example.stutter.server;

import com.example.stutter.client.GreetingService;
import com.example.stutter.shared.FieldVerifier;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * The server side implementation of the RPC service.
 */
@SuppressWarnings("serial")
public class GreetingServiceImpl extends RemoteServiceServlet implements
		GreetingService {

	public String greetServer(String input) throws IllegalArgumentException {
		// Verify that the input is valid. 
		if (!FieldVerifier.isValidName(input)) {
			// If the input is not valid, throw an IllegalArgumentException back to
			// the client.
			throw new IllegalArgumentException(
					"Name must be at least 4 characters long");
		}

		String serverInfo = getServletContext().getServerInfo();
		String userAgent = getThreadLocalRequest().getHeader("User-Agent");

		// Escape data from the client to avoid cross-site script vulnerabilities.
		input = escapeHtml(input);
		userAgent = escapeHtml(userAgent);

		return "Hello, " + input + "!<br><br>I am running " + serverInfo
				+ ".<br><br>It looks like you are using:<br>" + userAgent;
	}

	/**
	 * Escape an html string. Escaping data received from the client helps to
	 * prevent cross-site script vulnerabilities.
	 * 
	 * @param html the html string to escape
	 * @return the escaped string
	 */
	private String escapeHtml(String html) {
		if (html == null) {
			return null;
		}
		return html.replaceAll("&", "&amp;").replaceAll("<", "&lt;")
				.replaceAll(">", "&gt;");
	}
	
	public String stutter(String textField){
		
		int numberOfLines = 1;
		int stringOfEachLineCount = 0;
		boolean isRepeatedWords = false;
		String[] stringOfEachLine;
		String lastWord = "";
		String repeatedStringMessage = "";
		
		String input = textField;
		stringOfEachLine = input.split("\n");
		
		while (stringOfEachLineCount < stringOfEachLine.length ) {
			String line = stringOfEachLine[stringOfEachLineCount].replaceAll("[^a-zA-Z0-9 ]", "");
			line = line.toLowerCase();

			String[] words = line.split(" ");
			
			if (words[0].equals(lastWord)){
				repeatedStringMessage = repeatedStringMessage + "Repeated word on line " + numberOfLines + " : " + words[0] + "<br>";
				isRepeatedWords = true;

			}
			
			for (int i = 0; i < words.length - 1; i++) {
				if (words[i].equals(words[i + 1])){
					repeatedStringMessage = repeatedStringMessage +  "Repeated word on line " + numberOfLines + " : " + words[i] + "<br>";
					isRepeatedWords = true;
					
				}								
			}
			lastWord = words[words.length-1];
			stringOfEachLineCount++;
			numberOfLines++;
		}
		if(!isRepeatedWords){
			repeatedStringMessage = "No repeated words found";
		}
		return repeatedStringMessage;
	}
}
